package com.example.springmvceasybuy.controller;

import com.example.springmvceasybuy.entity.News;
import com.example.springmvceasybuy.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    NewsService newsService;
    @GetMapping
    // @RequestParam(required = false,defaultValue ="10")写在变量之前,表示没传该值,默认为defaultValue
    public String index(
                        @RequestParam(required = false,defaultValue ="") String title,
                        @RequestParam(required = false,defaultValue ="1") int pageIndex,
                        @RequestParam(required = false,defaultValue ="10") int pageSize,
                        Model model){
        // 添加参数，传递到页面
        model.addAttribute("pageInfo",newsService.selectAllByPage(title,pageIndex,pageSize));//request.setAttribute("news",news);
        //转发
        return "/news/index"; // WEB-INF/news/index.jsp
    }
    @GetMapping("/delete")
    public String delete(int id){
        //执行删除
        newsService.delete(id);
        //重定向到显示页面
        return "redirect:/news";
    }
    //进入新增页面方法
    @GetMapping("/insert")
    public String insert(){
        return "/news/insert";
    }
    //执行新增方法
    @PostMapping("/insert")
    public String doinsert(News news){
         newsService.doinsert(news);
        //重定向到显示页面
        return "redirect:/news";
    }
    @GetMapping("/update")
    //根据id查询要修改的新闻显示到修改页面
    public String selectbyid(int id,Model model){
        News news=newsService.selectbyid(id);
        // 添加参数，传递到页面
        model.addAttribute("news",news);//request.setAttribute("news",news);
        return "/news/update";
    }
    //修改新闻方法
    @PostMapping("/update")
    public String update(News news){
        newsService.update(news);
        //重定向到显示页面
        return "redirect:/news";
    }
}
